package niu.toy.spring.boot;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.SystemPropsUtil;
import niu.toy.spring.mvc.WebApplicationContext;
import niu.toy.spring.mvc.helper.ActionHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Properties;


/**
 * 启动一个web应用
 */
public class SpringApplication  {

    private static final Logger logger = LoggerFactory.getLogger(SpringApplication.class);


    /**
     * 启动 Web Server ，构建spring容器
     * @param primarySource 由此获得需扫描的basePackage
     * @return
     * @throws Exception
     */
    public static WebApplicationContext run(Class<?> primarySource) throws Exception {
        long start=System.currentTimeMillis();
        String basePackage=ClassUtil.getPackage(primarySource);
        logger.info("basePackage:{}",basePackage);
        WebApplicationContext context=new WebApplicationContext(basePackage);
        //扫描action bean 并填充字段
        ActionHelper.init(context.getBeanFactory());
        //读取配置
        Properties properties=new Properties();
        File configFile=new File(ClassUtil.getClassPath()+"/application.properties");
        if(configFile.exists())
            properties.load(IoUtil.toStream(configFile));

        String port=properties.getProperty("server.port");
        SystemPropsUtil.set("server.port", StrUtil.isBlank(port)?"8080":port.trim());

        String contextPath=properties.getProperty("server.servlet.contextPath");
        SystemPropsUtil.set("server.servlet.contextPath",StrUtil.isBlank(contextPath)?"":contextPath.trim());
        //启动 webServer
        context.createWebServer();
        logger.info("启动WebServer耗时:"+(System.currentTimeMillis()-start)/1000+"秒");
        return context;
    }

}
